﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using SQLite;
using MOJsdk;
using System.Collections.ObjectModel;
using System.Diagnostics;
using IO = System.IO;
using Microsoft.Win32;
using System.Threading;
using System.Windows.Threading;

namespace MOJ
{
    /// <summary>
    /// Interaction logic for Control_MovieDetails.xaml
    /// </summary>
    public partial class Control_MovieDetails : UserControl
    {
        private MOJMovie _movie;
        private ObservableCollection<MOJBasicFileClass> _files;
        private bool SelectImageWinShow = false;
        private bool SelectFileWinShow = false;
        private WindowControl _ctrl, _ctrl_selectFile;

        public Control_MovieDetails()
        {
            InitializeComponent();
            INI();
        }

        #region inicialization
        private void INI()
        {
            UnLoadMovie();
            INIElements();
            INIEvents();


        }
        private void INIElements()
        {
            #region Localization
            _lbl_cast.Content = MOJLocalization.Localize("Cast") + ": ";
            _lbl_director.Content = MOJLocalization.Localize("Director") + ": ";
            _lbl_files.Content = MOJLocalization.Localize("Files") + ": ";
            _lbl_genres.Content = MOJLocalization.Localize("Genres") + ": ";
            _lbl_tagline.Content = MOJLocalization.Localize("Tagline") + ": ";
            _lbl_title.Content = MOJLocalization.Localize("Title") + ": ";
            _lbl_writers.Content = MOJLocalization.Localize("Writers") + ": ";
            _lbl_year.Content = MOJLocalization.Localize("Year") + ": ";
            #endregion

            #region Style
            #region Buttons
            _btn_add.ApplyStyle("0101016");
            _btn_imdb.ApplyStyle("0101017");
            _btn_reload.ApplyStyle("0101018");
            _btn_remove.ApplyStyle("0101019");
            _btn_select.ApplyStyle("0101020");
            _btn_tmdb.ApplyStyle("0101021");
            #endregion
            #region Labels
            _lbl_cast.ApplyStyle("0101022");
            _lbl_director.ApplyStyle("0101023");
            _lbl_files.ApplyStyle("0101024");
            _lbl_genres.ApplyStyle("0101025");
            _lbl_tagline.ApplyStyle("0101026");
            _lbl_title.ApplyStyle("0101027");
            _lbl_writers.ApplyStyle("0101028");
            _lbl_year.ApplyStyle("0101029");
            #endregion
            #region TextBox
            _txtbox_directors.ApplyStyle("0101034");
            _txtbox_genres.ApplyStyle("0101035");
            _txtbox_maintitle.ApplyStyle("0101036");
            _txtbox_tagline.ApplyStyle("0101037");
            _txtbox_writers.ApplyStyle("0101038");
            _txtbox_year.ApplyStyle("0101039");

            #endregion

            _Grid_main.ApplyStyle("0101030");
            _image.ApplyStyle("0101031");
            _listBox_cast.ApplyStyle("0101032");
            _listView.ApplyStyle("0101033");
            _plitter.ApplyStyle("0101106");

            #endregion

            _btn_remove.IsEnabled = false;
            _listView.SelectionMode = SelectionMode.Single;
        }
        private void INIEvents()
        {
            _btn_imdb.Click += delegate { Process.Start(_movie.ImdbUrl); };
            _btn_tmdb.Click += delegate { Process.Start(_movie.TheMovieDbUrl); };
            this.Unloaded += ElemUnloaded;

            _listView.SelectionChanged += ListViewSelectionChanged;
            _listView.MouseDoubleClick += PlayMediaFile;

            _btn_remove.Click += BtnRemoveClicked;
            _btn_add.Click += BtnAddClicked;
            _btn_select.Click += BtnSelectImageClick;
            _btn_reload.Click += BtnReloadClick;

            foreach(var v in _Grid_main.Children)
            {
                if(v.GetType() == typeof(TextBox))
                {
                    ((TextBox)v).LostFocus += UpdateMovieDetails;
                }
            }
        }
        #endregion

        public void LoadMovie(string MovieID)
        {
            GlobalVars.TheHost.AddLogEntry("Start loading movie: " + MovieID);
            _Grid_main.IsEnabled = true;
            ClearStatus();
            _movie = new MOJMovie(MovieID);
            SetMovie();
        }
        public void UnLoadMovie()
        {
            _Grid_main.IsEnabled = false;
            ClearStatus();
            _movie = null;
        }
        public void ClearStatus()
        {
            _txtbox_directors.Clear();
            _txtbox_genres.Clear();
            _txtbox_maintitle.Clear();
            _txtbox_tagline.Clear();
            _txtbox_writers.Clear();
            _txtbox_year.Clear();
            _listBox_cast.Items.Clear();
            _image.Source = null;
            _files = new ObservableCollection<MOJBasicFileClass>();
            _listView.ItemsSource = _files;
        }
        private void SetMovie()
        {
            SetWaitStatus(true);
            NoArgsThread th = new NoArgsThread(SetMovieAsync);
            th.BeginInvoke(null, null);
        }
        private void SetMovieAsync()
        {
            Dispatcher.BeginInvoke(DispatcherPriority.Send, (ThreadStart)delegate
            {
                if (_movie == null)
                {
                    SetWaitStatus(false);
                    return;
                }

                ClearStatus();

                _txtbox_directors.Text = _movie.MovieDirectors;
                _txtbox_genres.Text = _movie.MovieGenres;
                _txtbox_maintitle.Text = _movie.MovieTitle;
                _txtbox_tagline.Text = _movie.Tagline;
                _txtbox_writers.Text = _movie.MovieWriters;
                _txtbox_year.Text = _movie.MovieYear;

                _files = new ObservableCollection<MOJBasicFileClass>(_movie.Files);
                _listView.ItemsSource = _files;

                _listBox_cast.Items.Clear();
                foreach (var s in _movie.Cast)
                    _listBox_cast.Items.Add(s);

                _image.Source = new BitmapImage(new Uri(_movie.MovieCoverPath));

                SetWaitStatus(false);
                GlobalVars.TheHost.AddLogEntry("Load Movie Completed");
            });
        }

        private void ListViewSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int index = _listView.SelectedIndex;

            if (index != -1)
            {
                _btn_remove.IsEnabled = true;
                GlobalVars.TheHost.sv_SelectedFile = _files[index].FileID.ToString();
            }
            else
            {
                _btn_remove.IsEnabled = false;
                GlobalVars.TheHost.sv_SelectedFile = "NULL";
            }
        }
        private void PlayMediaFile(object sender, MouseButtonEventArgs e)
        {
            int x = _listView.SelectedIndex;
            if (x == -1) return;

            MOJBasicFileClass f = _files[x];

            GlobalVars.TheHost.PlayFile(f.FileFullPath);
        }

        private void BtnRemoveClicked(object sender, RoutedEventArgs e)
        {
            int x = _listView.SelectedIndex;
            MOJBasicFileClass file = _files[x];

            if (file.FileID == _movie.CoverID)
            {
                if (_files.Where(z => z.FileType == 2 && z.FileID != file.FileID).Count() > 0)
                    _movie.CoverID = _files.First(z => z.FileType == 2 && z.DiskID != file.DiskID).FileID;
                else
                {
                    GlobalVars.TheHost.ShowMessage(MOJLocalization.Localize("Need at least one image"), MOJLocalization.Localize("Cant delete"));
                    return;
                }
            }

            GlobalVars.TheHost.RemoveFileFromDataBase(file.FileID);
            _movie = new MOJMovie(_movie.MovieCode);
            SetMovie();
        }
        private void BtnAddFile(object sender, RoutedEventArgs e)
        {
            _ctrl_selectFile.Close();
            OpenFileDialog diag = new OpenFileDialog();

            diag.Filter = TOOLS.GetFilesFilter();
            diag.Multiselect = true;
            diag.Title = MOJLocalization.Localize("Select files to import");

            if (diag.ShowDialog().Value)
            {
                foreach (string str in diag.FileNames)
                {
                    if (GlobalVars.TheHost.SystemVars.GetVar("VideoType").IndexOf(IO.Path.GetExtension(str).ToLower()) != -1)
                    {
                        if (_movie.MovieFiles.Where(z => z.FileFullPath == str).Count() == 0)
                            MOJBasicFileClass.AddNewMojBasicFile(str, MOJFileTypes.MovieFile, _movie.MovieCode);
                        else
                            GlobalVars.TheHost.ShowMessage("Movie file allready added", "Warning");
                    }
                    else if (GlobalVars.TheHost.SystemVars.GetVar("SubtitleType").IndexOf(IO.Path.GetExtension(str).ToLower()) != -1)
                    {
                        if (_movie.SubtitleFiles.Where(z => z.FileFullPath == str).Count() == 0)
                            MOJBasicFileClass.AddNewMojBasicFile(str, MOJFileTypes.SubtitleFile, _movie.MovieCode);
                        else
                            GlobalVars.TheHost.ShowMessage("Subtitle file allready added", "Warning");
                    }
                    else if (GlobalVars.TheHost.SystemVars.GetVar("ImageType").IndexOf(IO.Path.GetExtension(str).ToLower()) != -1)
                    {
                        if (_movie.ImageFiles.Where(z => z.FileFullPath == str).Count() == 0)
                            MOJBasicFileClass.AddNewMojBasicFile(str, MOJFileTypes.ImageFile, _movie.MovieCode);
                        else
                            GlobalVars.TheHost.ShowMessage("Image file allready added", "Warning");
                    }
                    else
                    {

                    }
                }

                _movie = new MOJMovie(_movie.MovieCode);
                SetMovie();
            }
        }
        private void BtnAddClicked(object sender, RoutedEventArgs e)
        {
            if (SelectFileWinShow)
                return;

            Control_SelectFile _select = new Control_SelectFile();
            _select.OnSearchFile += BtnAddFile;
            _select.OnFileSelected += SelectFile;

            _ctrl_selectFile = GlobalVars.TheHost.AddNewUserControl(_select, new WindowControlInfo(300, 400)
            {
                DefaultPosition = WindowPosition.Center,
                WindowTitle = MOJLocalization.Localize("Select File"),
            });

            _ctrl_selectFile.OnClosed += delegate { SelectFileWinShow = false; };

            SelectFileWinShow = true;
        }
        private void SelectFile(File2Add File, int Index)
        {
            _ctrl_selectFile.Close();

            ((Control_HandleFiles)GlobalVars.TheHost.GetElement("MOJ_managefiles")).RemoveAt(Index);
            string str = File.FilePath.ToLower();

            if (GlobalVars.TheHost.SystemVars.GetVar("VideoType").IndexOf(IO.Path.GetExtension(str).ToLower()) != -1)
            {
                if (_movie.MovieFiles.Where(z => z.FileFullPath.ToLower() == str).Count() == 0)
                    MOJBasicFileClass.AddNewMojBasicFile(str, MOJFileTypes.MovieFile, _movie.MovieCode);
                else
                    GlobalVars.TheHost.ShowMessage("Movie file allready added", "Warning");
            }
            else if (GlobalVars.TheHost.SystemVars.GetVar("SubtitleType").IndexOf(IO.Path.GetExtension(str).ToLower()) != -1)
            {
                if (_movie.SubtitleFiles.Where(z => z.FileFullPath.ToLower() == str).Count() == 0)
                    MOJBasicFileClass.AddNewMojBasicFile(str, MOJFileTypes.SubtitleFile, _movie.MovieCode);
                else
                    GlobalVars.TheHost.ShowMessage("Subtitle file allready added", "Warning");
            }

            _movie = new MOJMovie(_movie.MovieCode);
            SetMovie();
        }

        private void BtnSelectImageClick(object sender, RoutedEventArgs e)
        {
            if (SelectImageWinShow)
                return;
            SelectImageWinShow = true;

            Control_ImportImage ctrl = new Control_ImportImage();
            ctrl.OnImageSelected += OnImageSelected;
            ctrl.LoadImages(_movie.MovieCode);

            _ctrl = GlobalVars.TheHost.AddNewUserControl(ctrl, new WindowControlInfo(350, 300)
            {
                DefaultPosition = WindowPosition.Center,
                WindowTitle = "Select new Image",
            });
            _ctrl.OnClosed += delegate { SelectImageWinShow = false; };
        }
        private void OnImageSelected(MojWebImage IMAGE)
        {
            _ctrl.Close();
            IMAGE.DownloadOriginalFile();

            MOJBasicFileClass FILE = GlobalVars.TheHost.GetFile(_movie.CoverID);
            FILE.FilePath = IMAGE.OriginalPath;
            FILE.DiskID = TOOLS.GetDriveID(FILE.FilePath);

            using (SQLiteConnection _cn = new SQLiteConnection(GlobalVars.TheHost.SystemVars.DataBaseLocal))
            {
                _cn.Update(FILE, typeof(MOJBasicFileClass));
            }

            _movie = new MOJMovie(_movie.MovieCode);
            SetMovie();
        }

        private void BtnReloadClick(object sender, RoutedEventArgs e)
        {
            SetWaitStatus(true);
            NoArgsThread th = new NoArgsThread(ReloadMovieData);
            th.BeginInvoke(null, null);
        }
        private void ReloadMovieData()
        {
            MojWebMovie webmov = new MojWebMovie(new TheMovieDBV3.TmdbMovie(_movie.MovieCode));
            _movie.MovieTitle = webmov.Title;
            _movie.OriginalTitle = webmov.OriginalTitle;
            _movie.IMDBID = webmov.Imdb_Id;
            _movie.MovieCast = webmov.Cast.ToString(";");
            _movie.MovieDirectors = webmov.Director.ToString(";");
            _movie.MovieGenres = webmov.Genres.ToString(";");
            _movie.MovieWriters = webmov.Writer.ToString(";");
            _movie.MovieYear = webmov.Year;
            _movie.Tagline = webmov.Tagline;

            using(SQLiteConnection _cn = new SQLiteConnection(GlobalVars.TheHost.SystemVars.DataBaseLocal))
            {
                _cn.Update(_movie, typeof(MOJBasicMovieClass));
            }

            Dispatcher.BeginInvoke(DispatcherPriority.Send, (ThreadStart)delegate
            {
                SetMovie();
            });
        }

        private void UpdateMovieDetails(object sender, RoutedEventArgs e)
        {
            if (_movie == null)
            {
                UnLoadMovie();
                return;
            }

            if (!IsDiferent())
                return;

            _movie.MovieTitle = _txtbox_maintitle.Text;
            _movie.MovieDirectors = _txtbox_directors.Text;
            _movie.MovieGenres = _txtbox_genres.Text;
            _movie.MovieWriters = _txtbox_writers.Text;
            _movie.MovieYear = _txtbox_year.Text;
            _movie.Tagline = _txtbox_tagline.Text;

            using(SQLiteConnection _cn = new SQLiteConnection(GlobalVars.TheHost.SystemVars.DataBaseLocal))
            {
                MOJBasicMovieClass m = _movie;
                _cn.Update(m, typeof(MOJBasicMovieClass));
            }
        }
        private bool IsDiferent()
        {
            if (_movie.MovieTitle != _txtbox_maintitle.Text || _movie.MovieDirectors != _txtbox_directors.Text ||
                _movie.MovieGenres != _txtbox_genres.Text || _movie.MovieWriters != _txtbox_writers.Text ||
                _movie.MovieYear != _txtbox_year.Text || _movie.Tagline != _txtbox_tagline.Text)
                return true;

            return false;
        }

        private void SetWaitStatus(bool IsWait)
        {
            if (IsWait)
            {
                _Grid_main.IsEnabled = false;
            }
            else
            {
                _Grid_main.IsEnabled = true;
            }
        }

        private void ElemUnloaded(object sender, RoutedEventArgs e)
        {
            if (GlobalVars.TheHost.sv_DisplayPanel == "PanelDisplayMovies")
                GlobalVars.TheHost.ReloadElementsInfo();
        }

        private delegate void NoArgsThread();
    }
}
